package com.cold.demo.jsoup.ws;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class JavaWebSocketClient {


    public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException {
        JavaWebSocketClient clientProvider = new JavaWebSocketClient();
        WebSocketClient     client         = clientProvider.getClient("ws://foyoung.f3322.net:8089/ws/asset/6/8iTwRlqdncvYx6EGLkwE");
        if (client != null) {
            System.out.println("创建成功");
        }
    }

    /**
     * 获取客户端连接实例
     *
     * @param uri
     * @return
     */
    public WebSocketClient getClient(String uri) throws URISyntaxException, InterruptedException {
        WebSocketClient client = new WebSocketClient(new URI(uri), new Draft_6455()) {

            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                System.out.println("建立连接");
            }

            @Override
            public void onMessage(String s) {
                System.out.println("响应消息：" + s);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("关闭连接");
            }

            @Override
            public void onError(Exception e) {
                System.out.println("出现异常");
            }
        };

        System.out.println("连接中.......");
        //请求与服务端建立连接
//        client.connect();// 以异步的方式建立连接，该方法不会堵塞
        client.connectBlocking();// 以阻塞的方式建立连接，当线程被打断时将会抛出InterruptedException异常
        while (
                client.getReadyState() != ReadyState.OPEN
        ) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println("延迟操作出现问题，但并不影响功能");
            }
            System.out.println("连接中.......");
        }
        //连接状态不再是0请求中，判断建立结果是不是1已建立
        switch (client.getReadyState()) {
            case OPEN:
                return client;
            case CLOSED:
                System.out.println("已被关闭");
                break;
            case CLOSING:
                System.out.println("关闭中");
                break;
            case NOT_YET_CONNECTED:
                System.out.println("尚未连接");
                break;
        }
        return null;
    }
}
